package com.twotiger.and;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.twotiger.and.activity.HomeActivity;
import com.twotiger.and.activity.MainActivity;
import com.twotiger.and.activity.WebViewDialogPage;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.bean.Jpushbean2;
import com.twotiger.and.db.dao.JpushNoticeDao;
import com.twotiger.and.util.LogUtil;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class TwoTigerPushReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    private String title = "";
    private String id = "";
    private String target = "";
    private String type = "";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if(intent == null || bundle == null){
            return;
        }
        Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: "
                   + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {  //刚注册时的Registration ID
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) { //接收到推送的自定义消息
            
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) { //收到了通知 Push。
            long notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            LogUtil.info("notifactionId收到"+notifactionId);
            LogUtil.info("messageId收到" + bundle.getString(JPushInterface.EXTRA_MSG_ID));
            String notifactionAlert = bundle.getString(JPushInterface.EXTRA_ALERT);
            String notifactionTitle = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            String notifactionContent = bundle.getString(JPushInterface.EXTRA_EXTRA);
            
//            if(notifactionId < 0 ){
//                LogUtil.info("notifactionId不展示"+notifactionId);
//                JPushInterface.clearNotificationById(context, -notifactionId);
//                return;
//            }
            
            //收到通知消息，立即把消息存储到数据库
            JpushNoticeDao jpushNoticeDao = new JpushNoticeDao(context);
            jpushNoticeDao.addNotice(notifactionId, notifactionAlert,notifactionTitle, notifactionContent);
            
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {  //用户点击了通知。
            long notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            LogUtil.info("notifactionId点击"+notifactionId);
            String notifactionAlert = bundle.getString(JPushInterface.EXTRA_ALERT);
            String notifactionTitle = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            String notifactionContent = bundle.getString(JPushInterface.EXTRA_EXTRA);
            
            parscoustommsg(context, notifactionContent, notifactionTitle);
            
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(
                TAG,
                "[MyReceiver] 用户收到到RICH PUSH CALLBACK: "
                        + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE,
                false);
            Log.e(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to "
                       + connected);
        } else {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    private boolean checkAppIsRunning(Context context) {
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        String MY_PKG_NAME = "app.twotiger.p2p";
        for (RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
                isAppRunning = true;
                Log.i(TAG,info.topActivity.getPackageName() + " info.baseActivity.getPackageName()="+info.baseActivity.getPackageName());
                break;
            }
        }
        return isAppRunning;
    }
    
    private void cleanJpush(Context context){
        JpushNoticeDao jpushNoticeDao = new JpushNoticeDao(context);
        jpushNoticeDao.deleteNotice(); //清除数据库数据
    }

    private void parscoustommsg(Context context, String msg, String title) {
        
        if(checkAppIsRunning(context)){   //正在运行
            Jpushbean2 jpushbean2 = JSON.parseObject(msg, Jpushbean2.class);
            jpushbean2.setName(title);
            if(jpushbean2 != null && "link".equals(jpushbean2.getType())){
                if("alert".equals(jpushbean2.getStyle())){
                    cleanJpush(context);
                    Intent intent = new Intent(context, WebViewDialogPage.class);
                    intent.putExtra("PUSH", jpushbean2);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }else if("default".equals(jpushbean2.getStyle())){
                    cleanJpush(context);
                    Intent intent = new Intent(context, WebViewPage.class);
                    intent.putExtra("url", jpushbean2.getTarget());
                    intent.putExtra("title", jpushbean2.getName());
                    intent.putExtra("PUSH", jpushbean2);
                    intent.putExtra("BACK_MODE", WebViewPage.BACK_DIRECT); //webview的返回形式
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            }else if(jpushbean2 != null && "action".equals(jpushbean2.getType())){  //暂时不处理

            }
        }else {  //没有运行
            Jpushbean2 jpushbean2 = JSON.parseObject(msg, Jpushbean2.class);
            jpushbean2.setName(title);
            Intent intent = new Intent(context, MainActivity.class);
            intent.putExtra("PUSH", jpushbean2);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }
}
